import cv2

img = cv2.imread("./img/basic01.png")
# 灰度化处理
gray_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# 模糊处理(因为是简单图形的检测，不需要模糊)
ret,binary_img = cv2.threshold(gray_img,127,255,cv2.THRESH_BINARY)

# 寻找图形中的轮廓
contours,hierarchy = cv2.findContours(binary_img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

# 遍历所有查找的轮廓
for cont in contours:
    # 所有轮廓的近似矩形(内接矩形)
    x,y,w,h = cv2.boundingRect(cont)
    # 绘制所有矩形
    cv2.rectangle(img,(x,y),(x+w,y+h),color=(0,0,0),thickness=2)
    # 中心点坐标
    cx = int(x + w / 2)
    cy = int(y + h / 2)

    # 计算整个轮廓的周长
    peri = cv2.arcLength(cont, True)
    # 找近似的轮廓，例如：把0.04*周长的线段认为是一个边
    # 查找图形中内接顶点的数量.
    approx = cv2.approxPolyDP(cont, float(0.04) * peri, True)

    shape = ""
    # 内接顶点数量 == 3 三角形
    if len(approx) == 3:
        shape = "triangle"
    elif len(approx) == 4:
        shape = "rectangle"
    elif len(approx) > 4:
        shape = "circle"
    cv2.putText(img, shape, (cx, cy),0,1, color=(0, 0, 0), thickness=2)

cv2.imshow("src",img)
cv2.waitKey(0)